const mongoose = require('mongoose');

const bannerSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, '轮播图标题不能为空'],
    trim: true,
    maxlength: [100, '标题长度不能超过100个字符']
  },
  image: {
    type: String,
    required: [true, '轮播图图片不能为空'],
    trim: true
  },
  link: {
    type: String,
    trim: true,
    default: ''
  },
  linkType: {
    type: String,
    enum: ['product', 'category', 'shop', 'external', 'none'],
    default: 'none'
  },
  linkTarget: {
    type: String,
    trim: true,
    default: ''
  },
  order: {
    type: Number,
    default: 0,
    min: [0, '排序值不能小于0']
  },
  isActive: {
    type: Boolean,
    default: true
  },
  startDate: {
    type: Date,
    default: Date.now
  },
  endDate: {
    type: Date,
    default: null
  },
  clickCount: {
    type: Number,
    default: 0,
    min: [0, '点击次数不能小于0']
  },
  description: {
    type: String,
    trim: true,
    maxlength: [500, '描述长度不能超过500个字符'],
    default: ''
  },
  platform: {
    type: String,
    enum: ['mobile', 'web', 'all'],
    default: 'all'
  },
  createdBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  updatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// 索引
bannerSchema.index({ order: 1, isActive: 1 });
bannerSchema.index({ platform: 1, isActive: 1 });
bannerSchema.index({ startDate: 1, endDate: 1 });
bannerSchema.index({ createdAt: -1 });

// 虚拟字段：检查是否在有效期内
bannerSchema.virtual('isValid').get(function () {
  const now = new Date();
  const startValid = !this.startDate || this.startDate <= now;
  const endValid = !this.endDate || this.endDate >= now;
  return this.isActive && startValid && endValid;
});

// 静态方法：获取有效的轮播图
bannerSchema.statics.getActiveBanners = function (platform = 'all', limit = 10) {
  const now = new Date();
  const query = {
    isActive: true,
    $or: [
      { startDate: { $lte: now } },
      { startDate: { $exists: false } }
    ],
    $or: [
      { endDate: { $gte: now } },
      { endDate: { $exists: false } },
      { endDate: null }
    ]
  };

  if (platform !== 'all') {
    query.$or = [
      { platform: platform },
      { platform: 'all' }
    ];
  }

  return this.find(query)
    .populate('createdBy', 'name email')
    .populate('updatedBy', 'name email')
    .sort({ order: 1, createdAt: -1 })
    .limit(limit);
};

// 实例方法：增加点击次数
bannerSchema.methods.incrementClick = function () {
  this.clickCount += 1;
  return this.save();
};

// 中间件：保存前验证
bannerSchema.pre('save', function (next) {
  // 如果设置了结束时间，确保结束时间晚于开始时间
  if (this.endDate && this.startDate && this.endDate <= this.startDate) {
    const error = new Error('结束时间必须晚于开始时间');
    error.name = 'ValidationError';
    return next(error);
  }
  next();
});

// 中间件：删除前清理相关数据
bannerSchema.pre('remove', function (next) {
  // 这里可以添加删除轮播图时的清理逻辑
  // 比如删除相关的统计数据等
  next();
});

const Banner = mongoose.model('Banner', bannerSchema);

module.exports = Banner;
